package com.qsxc.system.config.common;

import com.qsxc.business.bean.R;
import com.qsxc.utils.CollectionUtil;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description: @Vaild注解抛出自定义异常
 * @author: chenhongwei
 * @date: 2021-07-15
 *
 */
@ControllerAdvice
public class VaildExceptionConfig {

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R throwCustomException(MethodArgumentNotValidException methodArgumentNotValidException) {
        if (methodArgumentNotValidException.getBindingResult() != null) {
            if (!CollectionUtil.isEmpty(methodArgumentNotValidException.getBindingResult().getFieldErrors())) {
                return R.fail(methodArgumentNotValidException.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
            }
        }
        return R.fail("请填写必填项目！");
    }
}
